package com.zany.util.file;

import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.Fields;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.struts2.ServletActionContext;

import com.zany.util.ZanyErrorMsg;
import com.zany.util.ZanyException;
import com.zany.util.date.DateFormater;
import com.zany.util.json.BeanInfoUtil;


public class FileUtil {
	
    private FileUtil() {
    }

    /**
     * 上传文件
     * 
     * @param fileKey       服务器文件路径KEY值
     * @param fileName      文件名称（带扩展名，如xx.doc）
     * @param sourceFile    上传源文件对象
     * @throws IOException
     * @throws WMSBizException 
     */
    public static void uploadFile(FileUploadPath.FileKey fileKey, String fileName, File sourceFile)  throws IOException {
        String path = FileUploadPath.getUploadFilePath(fileKey);
        File saveTo = new File(path + fileName);
        buildPath(path);               // 建路径 
        if (sourceFile.length() != 0) {
            copy(sourceFile, saveTo);
        }
    }
    public static void uploadFile(String fileName, File sourceFile, String path)  throws IOException {
    	File saveTo = new File(path + fileName);
        buildPath(path);               // 建路径 
        if (sourceFile.length() != 0) {
        	copy(sourceFile, saveTo);
        }
    }
    public static void uploadFile(FileUploadPath.FileKey fileKey, String fileName, File sourceFile, String path)  throws IOException {
        if(path==null||path==""){
        	path = FileUploadPath.getUploadFilePath(fileKey);
        }
        File saveTo = new File(path + fileName);
        buildPath(path);               // 建路径 
        if (sourceFile.length() != 0) {
        	copy(sourceFile, saveTo);
        }
    }
    /**
     * 上传文件
     * 
     * @param fileKey       服务器文件路径KEY值
     * @param fileName      文件名称（带扩展名，如xx.doc）
     * @param sourceFile    上传源文件路径
     * @throws IOException
     */
    public static void uploadFile(FileUploadPath.FileKey fileKey, String fileName, String sourceFilePath)  throws IOException {
        String path = FileUploadPath.getUploadFilePath(fileKey);
        
        String saveTo = path + fileName;
        buildPath(path);               // 建路径 
        copy(sourceFilePath, saveTo);
    }
    
    /**
     * 给上传文件的文件名打上时间戳
     * @param fileName   文件名
     * @return 打上时间戳的文件名
     */
    public synchronized static String generalFileName(String fileName) {
        if(fileName == null) {
            fileName = "";
        }
        String extendtion = "";        
        int pos = fileName.lastIndexOf(".");
        if(pos != -1) {
            extendtion = getExtention(fileName);
        }        
        fileName = getFileNameWithNoExtention(fileName);
        String now = DateFormater.formatDate("yyyyMMddHHmmssSSS");       
        String result = fileName + "_" + now;
        if(pos != -1) {
            result = result + extendtion;
        }       
        return result ;
    }
    
    /**
     * 建立路径，能够递归，如果存在，那么不再创建
     * 
     * @param ps_path
     *            String 要建立的路径字符串
     * 
     * @throws IOException
     * @return String 返回路径
     */
    public static String buildPath(String ps_path) throws IOException {
        File file = new File(ps_path);
        if (!file.exists())
            file.mkdirs();
        return file.getPath();
    }

    /**
     * 判断文件、目录是否存在
     * 
     * 
     * @param ps_file
     *            String 文件、目录名
     * @return boolean 存在返回true,否则返回false
     */
    public static boolean fileExist(String ps_file) {
        File f = new File(ps_file);
        return f.exists();
    }

    /**
     * 取得文件的路径，不包含文件名
     * 
     * @param ps_file
     *            String 包含文件名的文件路径
     * @return String 文件路径
     */
    public static String getFilePath(String ps_file) {
        File f = new File(ps_file);
        if (f.exists())
            return f.getParent();
        else
            return "";
    }

    /**
     * 取得给定目录下的所有文件
     * 
     * 
     * @param ps_path
     *            String 给定的目录
     * 
     * @return List 所有文件列表
     * 
     */
    public static List fetchSubFiles(String ps_path) {
        if (fileExist(ps_path)) {
            List list = new ArrayList();
            File file = new File(ps_path);
            File[] fs = file.listFiles();
            if (fs != null)
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].isFile())
                        list.add(fs[i]);
                }
            return list;
        } else
            return null;
    }

    /**
     * 取得给定目录下的符合过滤条件的所有文件
     * 
     * 
     * @param ps_path
     *            String 给定的目录
     * 
     * @param po_filter
     *            FileFilter 文件过滤器
     * 
     * @return List 所有符合条件的文件列表
     */
    public static List fetchSubFiles(String ps_path, FilenameFilter po_filter) {
        if (fileExist(ps_path)) {
            List list = new ArrayList();
            File file = new File(ps_path);
            File[] fs = file.listFiles(po_filter);
            if (fs != null)
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].isFile())
                        list.add(fs[i]);
                }
            return list;
        } else
            return null;
    }

    /**
     * 取得给定目录下的符合文件名后缀的所有文件
     * 
     * 
     * @param ps_path
     *            String 给定的目录
     * 
     * @param ps_suffix
     *            String 文件名后缀
     * @return List 所有符合条件的文件列表
     */
    public static List fetchSubFiles(String ps_path, String ps_suffix) {
        if (!ps_suffix.startsWith("."))
            ps_suffix = "." + ps_suffix;
        ps_suffix = ps_suffix.toLowerCase();
        if (fileExist(ps_path)) {
            List list = new ArrayList();
            File file = new File(ps_path);
            File[] fs = file.listFiles();
            if (fs != null)
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].isFile() && fs[i].getName().endsWith(ps_suffix))
                        list.add(fs[i]);
                }
            return list;
        } else
            return null;
    }

    /**
     * 取得给定目录下的所有子目录
     * 
     * @param ps_path
     *            String 给定的目录
     * 
     * @return List 所有子目录列表
     */
    public static List fetchSubDirs(String ps_path) {
        if (fileExist(ps_path)) {
            List list = new ArrayList();
            File file = new File(ps_path);
            File[] fs = file.listFiles();
            if (fs != null)
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].isDirectory())
                        list.add(fs[i]);
                }
            return list;
        } else
            return null;
    }

    /**
     * 删除文件
     * 
     * @param file_path
     *            String 文件的绝对路径
     * 
     * 
     */
    public static void deleteFile(String file_path) {

    	File file = new File(file_path);
    	
    	if(file.isFile() && file.exists()){    
            file.delete();
    	}
    	
    }

    /**
     * 文件拷贝。
     * 
     * 
     * @param from
     *            源路径。
     * 
     * @param to
     *            目标路径。
     * 
     * @exception IOException
     *                Description of the Exception
     */
    public static void copy(String from, String to) throws IOException {
        int BUFF_SIZE = 100000;
        byte[] buffer = new byte[BUFF_SIZE];
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(from);
            out = new FileOutputStream(to);
            while (true) {
                synchronized (buffer) {
                    int amountRead = in.read(buffer);
                    if (amountRead == -1) {
                        break;
                    }
                    out.write(buffer, 0, amountRead);
                }
            }
        } finally {
            if (in != null) {
                in.close();
            }

            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 返回指定文件的输出对象
     * 
     * 
     * @param fileName
     *            文件名
     * 
     * @return 文件输出对象
     * @throws IOException
     */
    public static Writer createFileW(String fileName) throws IOException {
        BufferedWriter os = null;
        try {
            os = new BufferedWriter(new FileWriter(fileName));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return os;
    }

    /**
     * 把buffer的内容写到Writer中
     * 
     * 
     * @param os
     *            Writer输出对象
     * @param buffer
     *            输出内容
     * @return 新的文件输出对象
     */
    public static Writer writeTo(Writer os, StringBuffer buffer) {
        try {
            os.write(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return os;
    }

    /**
     * 保存,关闭文件输出对象Writer
     * 
     * @param os
     *            文件输出对象Writer
     */
    public static void closeFileW(Writer os) {
        try {
            if (os != null) {
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 把内容写入文件，如果文件路径不在，自动创建
     * 
     * 
     * @param fileName
     *            文件名
     * 
     * @param buffer
     *            内容
     * @throws IOException
     *             异常
     */
    public static void saveToFile(String fileName, StringBuffer buffer)
            throws IOException {
        String temp = fileName;
        temp = temp.replace("\\", "/");
        temp = temp.substring(0, temp.lastIndexOf("/"));
        if (!fileExist(temp))
            buildPath(temp);
        Writer os = createFileW(fileName);
        os = writeTo(os, buffer);
        closeFileW(os);
    }

    /**
     * 文件拷贝
     * 
     * @param src
     *            源文件对象
     * @param dst
     *            目标文件对象
     */
    public static void copy(File src, File dst) {
        int BUFFER_SIZE = 16 * 1024;
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                byte[] buffer = new byte[BUFFER_SIZE];
                out = new BufferedOutputStream(new FileOutputStream(dst),
                        BUFFER_SIZE);
                if (src.exists()) {
                    in = new BufferedInputStream(new FileInputStream(src),
                            BUFFER_SIZE);
                    int byteRead = 0;
                    while ((byteRead = in.read(buffer)) > 0) {
                        out.write(buffer, 0, byteRead);
                    }
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取得文件的后缀名
     * 
     * 
     * @param fileName
     *            文件名
     * 
     * @return 返回后缀名，带.的那种
     * 
     */
    public static String getExtention(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if (pos != -1)
            return fileName.substring(pos);
        else
            return ".";
    }

    /**
     * 返回不带后缀名，也没有路径的文件名
     * 
     * 
     * @param fileName
     * @return
     */
    public static String getFileNameWithNoExtention(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if (pos != -1) {
            int po = fileName.lastIndexOf("\\");
            return fileName.substring(po + 1, pos);
        } else
            return fileName;
    }

    public static String getLastPathName(String filePath) {
        String result = "";
        filePath = filePath.replace("\\", "/");
        if (filePath.endsWith("/"))
            filePath = filePath.substring(0, filePath.lastIndexOf("/"));
        int pos1 = filePath.lastIndexOf("/");
        result = filePath.substring(pos1 + 1);
        return result;
    }
    
    // 根据key读取value(相对路径)
	public static String readValueRelative(String filePath, String key) {
		Properties props = new Properties();
		try {
			ClassLoader classLoader = FileUtil.class.getClassLoader();
			InputStream inputStream = classLoader.getResourceAsStream(filePath);
			props.load(inputStream);
			String value = props.getProperty(key);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
    // 读取properties的全部信息(相对路径)
    public static Map<String,String> readPropertiesRelative(String filePath) {
     Properties props = new Properties();
     Map<String,String> map = new HashMap<String,String>();
		try {
			ClassLoader classLoader = FileUtil.class.getClassLoader();
			InputStream inputStream = classLoader.getResourceAsStream(filePath);
			props.load(inputStream);
			Enumeration en = props.propertyNames();
			while (en.hasMoreElements()) {
				String key = (String) en.nextElement();
				String Property = props.getProperty(key);
				map.put(key, Property);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
    }
    
    // 读取properties的全部信息(绝对路径)
    public static Map<String,String> readPropertiesAbsolute(String filePath) {
     Properties props = new Properties();
     Map<String,String> map = new HashMap<String,String>();
		try {
			InputStream inputStream = new BufferedInputStream (new FileInputStream(filePath));
			props.load(inputStream);
			Enumeration en = props.propertyNames();
			while (en.hasMoreElements()) {
				String key = (String) en.nextElement();
				String Property = props.getProperty(key);
				map.put(key, Property);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
    }
    
  // 根据key读取value(绝对路径)
	public static String readValue(String filePath, String key) {
		Properties props = new Properties();
		try {
			InputStream in = new BufferedInputStream(new FileInputStream(filePath));
			props.load(in);
			return props.getProperty(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	

    
    // 读取properties的全部信息
       public static Properties readProperties(String filePath) {
        Properties props = new Properties();
           try {
            InputStream in = new BufferedInputStream (new FileInputStream(filePath));
            props.load(in);
               Enumeration en = props.propertyNames();
                while (en.hasMoreElements()) {
                 String key = (String) en.nextElement();
                   }
           } catch (Exception e) {
            e.printStackTrace();
           }
           return props;
       }

       //写入properties信息
       public static void writeProperties(String filePath, String parameterName,
			String parameterValue) {
		Properties prop = new Properties();
		try {
			InputStream fis = new FileInputStream(filePath);
			// 从输入流中读取属性列表（键和元素对）
			prop.load(fis);
			// 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
			// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
			OutputStream fos = new FileOutputStream(filePath);
			prop.setProperty(parameterName, parameterValue);
			// 以适合使用 load 方法加载到 Properties 表中的格式，
			// 将此 Properties 表中的属性列表（键和元素对）写入输出流
			prop.store(fos, "Update '" + parameterName + "' value");
		} catch (IOException e) {
			System.err.println("Visit " + filePath + " for updating "
					+ parameterName + " value error");
		}
	}

    /**
     * 删除文件
     * @param fileKey
     * @param fileName
     * @return
     * @throws UnsupportedEncodingException
     * @throws WMSBizException
     */
    public static boolean deleteFile(FileUploadPath.FileKey fileKey, String fileName) throws UnsupportedEncodingException{
    	String path = FileUploadPath.getUploadFilePath(fileKey);
        File saveTo = new File(path + fileName);
        if(saveTo.exists()){
        	return saveTo.delete();
        }
        return false;
    }
    
    /**
	 * 取得WebRoot路径
	 * @return
	 */
	public static String getWEBRootpath() {
		String filePath = FileUtil.class.getResource("").toString();
		//logger.warn("本类所在路径：" + filePath);
		// output demo:
		// file:/E:/WebWork/hdfjqb/WebRoot/WEB-INF/classes/com/freedom/fjmyx/util/
		filePath = filePath.substring(6, filePath.indexOf("WEB-INF"));
		return filePath;
	}
	
	public static void downFile(String url, String fileName, HttpServletResponse response) throws ZanyException{
		try {
			File file = new File(url);
			response.reset();
            response.setContentType("bin");
            response.setHeader("Content-Disposition","attachment; filename=\"" + new String(fileName.getBytes("GBK"), "ISO8859_1") + "\"");			
            OutputStream out = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fis.read(data);
            fis.close();
            out.write(data);
            out.flush();
            out.close();
		} catch (IOException e) {			
			e.printStackTrace();
		}
	}
	
	
	public static void writeInfoToPage(String str){
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/xml; charset=UTF-8"); 
		try {
			response.getWriter().write(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void listToExcel(HttpServletRequest request,HttpServletResponse response,String reportName,List list,String[][] header) throws ZanyException {
		OutputStream httpOut=null;
		try{
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setDateHeader("Expires", 0);
			response.setHeader("Content-Disposition","attachment;filename=\""+""+URLEncoder.encode(reportName, "UTF-8")+".xls\"");
			httpOut = response.getOutputStream();
			ExcelUtil.exportExcel(httpOut,reportName,header,list);
		}catch(Exception e){
			throw new ZanyException(ZanyErrorMsg.ERR_DEFAULT,e.getMessage(),e);
		}finally {
			try {
				httpOut.close();
			}catch (IOException e) {
				throw new ZanyException(ZanyErrorMsg.FILE_ERROR,e.getMessage(),e);
			}
		}
	}
	/**
	 * 将map写入EXCEL
	 * @param map
	 *            
	 * @param path 
	 *            路径
	 * @param targetFileName 
	 *            源文件名
	 * @param generateFileName          
	 *            生成文件名
	 * @throws ZanyException
	 */
	public static void mapToExcel(Map map,String path,String targetFileName,String generateFileName) throws ZanyException{
		XLSTransformer transformer = new XLSTransformer();
		try {
			transformer.transformXLS(path+targetFileName, map, path+generateFileName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 将list写入TXT
	 * @param list
	 *            list<vo>
	 * @param path 
	 *            路径
	 * @throws ZanyException
	 */
	public static void writeListToTxt(List list,String path) throws ZanyException{
		try{
			File file = new File(path);
			if(!file.exists()){
				file.createNewFile();
			}
			String bufferStr = new String();
			for(int i=0;i<list.size();i++){
				Object obj = list.get(i);
				PropertyDescriptor[] props = BeanInfoUtil.getPropertyDescriptors(obj);
				for (int j = 0; j < props.length; j++) {
					if(BeanInfoUtil.rightName(props[j])){
						Object value=props[j].getReadMethod().invoke(obj,null);
						String val = "";
						if(value instanceof java.lang.Double){
							val = new BigDecimal(BeanInfoUtil.getReadMethod(props[j]).invoke(obj,null)==null?"0":BeanInfoUtil.getReadMethod(props[j]).invoke(obj,null).toString()).toString();
						}else{
							val = BeanInfoUtil.getReadMethod(props[j]).invoke(obj,null)==null?"":BeanInfoUtil.getReadMethod(props[j]).invoke(obj,null).toString();
						}					
						bufferStr += val.trim();
						if(j+1==props.length){
							bufferStr += "\n";
						}else{
							bufferStr += "|";
						}
					}
				}
			}
			
			BufferedWriter output = new BufferedWriter(new FileWriter(file));
			output.write(bufferStr);
			output.close();
		}catch(Exception e){
			throw new ZanyException(ZanyErrorMsg.FILE_ERROR,e.getMessage(),e);
		}	
	}
	
	public static void stringToTxt(String bufferStr,String path) throws ZanyException{
		try{
			File file = new File(path);
			if(!file.exists()){
				file.createNewFile();
			}
			BufferedWriter output = new BufferedWriter(new FileWriter(file));
			output.write(bufferStr);
			output.close();
		}catch(Exception e){
			throw new ZanyException(ZanyErrorMsg.FILE_ERROR,e.getMessage(),e);
		}	
	}
	
	
	public static void writeWord(Map<String,String> map,String filePath,String targetFileName,String generateFileName){  
        //读取word模板  
//        String fileDir = new File(base.getFile(),"http://www.cnblogs.com/http://www.cnblogs.com/../doc/").getCanonicalPath();  
        FileInputStream in = null;  
        try {  
            in = new FileInputStream(new File(filePath+targetFileName));  
        } catch (FileNotFoundException e1) {  
            e1.printStackTrace();  
        }  
        HWPFDocument hdt = null;  
        try {  
            hdt = new HWPFDocument(in);  
        } catch (IOException e1) {  
            e1.printStackTrace();  
        }  
        Fields fields = hdt.getFields();  
        Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();  
      
        //读取word文本内容  
        Range range = hdt.getRange();  
        //替换文本内容  
        for (Map.Entry<String,String> entry: map.entrySet()) {  
            range.replaceText("$" + entry.getKey() + "$",entry.getValue());  
        }  
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();  
        FileOutputStream out = null;  
        try {  
            out = new FileOutputStream(filePath+generateFileName,true);  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }  
        try {  
            hdt.write(ostream);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        //输出字节流  
        try {  
            out.write(ostream.toByteArray());  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        try {  
            out.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        try {  
            ostream.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
	

    /** 
     * 实现对word读取和修改操作 
     * @param response    响应,设置生成的文件类型,文件头编码方式和文件名,以及输出 
     * @param filePath    word模板路径和名称 
     * @param map        待填充的数据，从数据库读取 
     * @throws UnsupportedEncodingException 
     */  
    public static void loadWord(HttpServletResponse response,Map<String,String> map,String filePath,String targetFileName,String generateFileName) throws UnsupportedEncodingException{  
        //读取word模板文件  
//        String fileDir = new File(base.getFile(),"http://www.cnblogs.com/http://www.cnblogs.com/../doc/").getCanonicalPath();  
//        FileInputStream in = new FileInputStream(new File(fileDir+"/laokboke.doc"));  
        FileInputStream in;  
        HWPFDocument hdt = null;  
        try {  
            in = new FileInputStream(new File(filePath+targetFileName));  
            hdt = new HWPFDocument(in);  
        } catch (Exception e1) {  
            e1.printStackTrace();  
        }  
          
        Fields fields = hdt.getFields();  
        Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();  
        while(it.hasNext()){  
            System.out.println(it.next().getType());  
        }  
  
        //替换读取到的word模板内容的指定字段  
        Range range = hdt.getRange();  
  
        for (Map.Entry<String,String> entry:map.entrySet()) {  
            range.replaceText("$" + entry.getKey() + "$",entry.getValue());  
        }  
  
        //输出word内容文件流，提供下载  
        response.reset();  
        response.setContentType("application/x-msdownload");  
        //response.addHeader("Content-Disposition", "attachment; filename="+generateFileName);  
        response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(generateFileName.getBytes("GBK"), "ISO8859_1") + "\"");	
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();  
        OutputStream servletOS = null;  
        try {  
            servletOS = response.getOutputStream();  
            hdt.write(ostream);  
            servletOS.write(ostream.toByteArray());  
            servletOS.flush();  
            servletOS.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }
}
